package com.shlh.saas.controller;

import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.EmailLookupService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/email-lookup")
public class EmailLookupController {

    private static final Logger log = LoggerFactory.getLogger(EmailLookupController.class);

    @Autowired
    private EmailLookupService emailLookupService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;

    @GetMapping("")
    public Map<String, Object> lookupByValue(
            @RequestParam String value,
            @RequestParam String type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 添加详细调试日志
        log.info("收到邮件/电话反查请求: 值={}, 类型={}, 页码={}, 页大小={}", value, type, page, size);

        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            
            // 基础参数验证
            if (value == null || value.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("results", Collections.emptyList());
                errorResponse.put("total", 0);
                errorResponse.put("page", page);
                errorResponse.put("size", size);
                errorResponse.put("error", "查询值不能为空");
                return errorResponse;
            }
            
            // 电话/邮箱反查属于特殊操作，无论是第几页都需要扣除额度
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() < size) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("results", Collections.emptyList());
                errorResult.put("total", 0);
                errorResult.put("page", page);
                errorResult.put("size", size);
                errorResult.put("error", "您的反查次数余额不足，请充值后再查看");
                return errorResult;
            }
            
            // 调用服务进行查询
            Map<String, Object> result = emailLookupService.lookupByValue(value, type, page, size);
            log.info("查询结果总数: {}", result.containsKey("total") ? result.get("total") : "未知");
            
            // 获取实际返回的数据条数
            int actualCount = 0;
            if (result.containsKey("results") && result.get("results") instanceof List) {
                List<?> resultList = (List<?>) result.get("results");
                actualCount = resultList.size();
                log.info("实际返回数据条数: {}", actualCount);
            } else {
                log.warn("返回结果中不含'results'键或不是List类型");
            }
            
            // 扣除用户反查余额
            if (actualCount > 0) {
                boolean deducted = userBalanceService.deductReverseLookup(userId, actualCount);
                if (deducted) {
                    log.info("成功扣除用户ID={}的反查次数{}次", userId, actualCount);
                    
                    // 增加邮件/电话反查次数统计
                    if ("email".equals(type)) {
                        workbenchStatsService.incrementEmailReverseCount(userId);
                    }
                } else {
                    log.warn("扣除用户ID={}的反查次数失败", userId);
                }
            } else {
                log.info("无有效数据返回，不扣除用户余额");
            }
            
            return result;
        } catch (Exception e) {
            log.error("处理邮件/电话反查请求时发生异常", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("results", Collections.emptyList());
            errorResult.put("total", 0);
            errorResult.put("page", page);
            errorResult.put("size", size);
            errorResult.put("error", "处理请求时发生错误: " + e.getMessage());
            return errorResult;
        }
    }
} 